<template>
  <div id="wxdetail">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">时间:</span>
          <datePickerYmd @on-change="doSearch"
                         :selectDateType.sync='selectDateType'
                         :dateOption="dateOption"
                         v-model="timeDate"
                         style="display:inline-block"></datePickerYmd>
          <!-- <RadioGroup v-model="button"
                      type="button"
                      @on-change="doSearch">
            <Radio label="日"></Radio>
            <Radio label="月"></Radio>
          </RadioGroup>
          <DatePicker v-if="button==='日'"
                      type="date"
                      format="yyyy-MM-dd"
                      placement="bottom"
                      class="wxdetail-style"
                      :editable="false"
                      :clearable="false"
                      :value="startTimeDay"
                      @on-change="selectStartDay"
                      :options="optionsStartTimeDay"></DatePicker>
          <DatePicker v-if="button==='月'"
                      type="month"
                      format="yyyy-MM"
                      placeholder="Select month"
                      class="wxdetail-style"
                      :editable="false"
                      :clearable="false"
                      :value="startTimeMonth"
                      @on-change="selectStartMonth"
                      :options="optionsStartTimeMonth"></DatePicker> -->
          </Col>
          <Col class="search-item"
               style="display:flex;">
          <span class="search-label"
                style="display: inline-block;padding-top: 7px">门店名称:</span>
          <vueTreeselectChoice :max-tag-count='1'
                               componentsType='iselect'
                               :filterable="true"
                               @on-change="doSearch"
                               permissionCode="moms:report:dailyanalytics"
                               v-model="shopId"></vueTreeselectChoice>
          <!-- <vueTreeselectChoice :disable-branch-nodes="true"
                               style="display:inline-block"
                               :clearable='false'
                               @on-api-finish='setshopId'
                               @input='doSearch'
                               permissionCode="moms:report:dailyanalytics"
                               v-model="shopId"></vueTreeselectChoice> -->
          <!-- <Select v-model="shopId"
                  class="select-shop-item"
                  @on-change="doSearch"
                  filterable>
            <Option v-for="item in shopListData"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option> -->
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="doSearch">查询</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <div style="position:relative;width:100%;">
      <Row type="flex"
           justify="start"
           class="search-box-title">
        <span class="system-selete-icon"></span>
        <span class="system-selete-title">微信销售统计</span>
      </Row>
      <div class="wxdetail-chart-div"
           v-show="weChatShow">
        <div class="chart-pie">
          <div id="paymentTerm"></div>
        </div>
        <div class="wxdetail-chart-legend">
          <div class="legend-li"
               v-for="(item,index) in weChatSalesStatisticsData"
               :key="index">
            <span class="legend-icon"
                  :style="{'background-color':item.color}"></span>
            <span class="legend-title">{{item.productName}}<span>{{'('+parseFloat(item.consumeTimes).toFixed(0)+'笔)'}}</span></span>
            <span class="legend-total">{{item.consumeAmount}}</span>
            <span class="legend-percentage">{{item.amountRate}}%</span>
          </div>
          <div class="legend-li">
            <span class="legend-icon"
                  style="background-color: #17233D;"></span>
            <span class="legend-title">合计</span>
            <span class="legend-total">{{totalAmount}}</span>
          </div>
        </div>
      </div>
      <div class="wxdetail-chart-div"
           v-show="!weChatShow"
           style="text-align: center;padding:20px 0;">
        <img :width="320"
             :height="240"
             :src="error">
      </div>
      <Row type="flex"
           justify="start"
           class="search-box-title">
        <span class="system-selete-icon"></span>
        <span class="system-selete-title">微信销售明细</span>
      </Row>
      <div class="wxdetail-table">
        <Table :loading="loading"
               :height="this.tableHeight"
               :columns="columns"
               :data="wechatData">
          <!-- 电子码 -->
          <template slot-scope="{ row }"
                    slot="code">
            <span>{{row.code!=="" && row.code!==null?"XXXXXXX"+row.code.substr(row.code.length-2,2):""}}</span>
          </template>
          <!-- 游戏币数 -->
          <template slot-scope="{ row }"
                    slot="amount">
            <span>{{row.amount!=="" && row.amount!==null?parseFloat(row.amount).toFixed(0):0}}</span>
          </template>
        </Table>
        <div class="page-box"
             style="margin-top: 20px">
          <Page :total="total"
                ref="pages"
                :current.sync="pageIndex"
                :page-size="pageSize"
                @on-change="handlePage"
                @on-page-size-change="handlePageSize"
                show-sizer
                show-total />
        </div>
      </div>
      <Spin size="large"
            fix
            v-if="spinShow"></Spin>
    </div>
  </div>
</template>
<script>
import echarts from 'echarts'
import { getShopList } from '@/api/system/store'
import { wechatmallSalesDaily, wechatmallSalesList } from '@/api/report/finance'
import error from '@/assets/images/error-page/error.svg'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
export default {
  name: 'report_finance_dailyanalytics_wxdetail',
  components: { vueTreeselectChoice, datePickerYmd },
  data () {
    return {
      spinShow: false, // loading
      loading: false,
      tableHeight: 0, // 表高度
      selectDateType: 'daterange',
      timeDate: [dayjs(this.$route.params.dateTime).format('YYYY-MM-DD 00:00:00'), dayjs(this.$route.params.dateTime).format('YYYY-MM-DD 00:00:00')],
      button: '日',
      shopName: '',
      shopListData: [], // 门店列表
      weChatShow: true, // 微信销售统计
      weChatSalesStatisticsData: [], // 微信销售统计
      chartColor: ['#2D8CF0', '#2D56F9', '#6A7FD1', '#18BE6B', '#BABE18', '#5A9F46', '#FF9901', '#FFBB01', '#FFBB01', '#C42DF0', '#F02D96', '#8559BA', '#ED4014', '#EDE614', '#D49955'],
      shopId: this.$route.params.shopId ? this.$route.params.shopId : null, // 门店ID
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      error: error,
      totalAmount: 0, // 微信销售统合计
      dateOption: {
        disabledDate (date) {
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      columns: [
        {
          title: '消费时间',
          key: 'createTime'
        },
        {
          title: '电子码',
          slot: 'code'
        },
        {
          title: '游戏币数',
          slot: 'amount'
        },
        {
          title: '地点',
          key: 'createPosName'
        }
      ],
      wechatData: [],
      optionsStartTimeDay: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      },
      optionsStartTimeMonth: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now() - 86400000
        }
      }
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      if (this.selectDateType === 'daterange') return dayjs(this.timeDate[1]).add(1, 'day').format('YYYY-MM-DD 00:00:00')
      return this.timeDate[1]
    }
  },
  created () { },
  methods: {
    // 图表
    initChart () {
      let myChart = echarts.init(document.getElementById('paymentTerm')) // 收款方式
      let option = {
        title: {
          text: '微信销售',
          x: 'center',
          y: 'center',
          textStyle: {
            color: '#808695',
            fontFamily: '微软雅黑',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}：{d}%'
        },
        color: this.chartColor,
        series: [
          {
            name: '收款方式',
            type: 'pie',
            radius: ['30%', '55%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: this.weChatSalesStatisticsData
          }
        ]
      }
      myChart.setOption(option) // 收款方式
      window.addEventListener('resize', function () {
        myChart.resize() // 收款方式
      })
    },
    // 查询按钮
    doSearch () {
      if (this.shopId !== '') {
        this.spinShow = true
        this.tableHeight = 0
        this.getwechatmallSalesDaily()
        this.getwechatmallSalesList()
      } else {

      }
    },
    setshopId () {
      this.shopId = this.$route.params.shopId ? this.$route.params.shopId : null
    },
    // 重置
    resetBtn () { },
    // 分页操作
    handlePage (val) {
      this.pageIndex = val
      this.getwechatmallSalesList()
    },
    handlePageSize (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getwechatmallSalesList()
    },
    // 查询门店名称
    getShopList () {
      getShopList({
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      })
        .then(res => {
          if (res.data.status === 200) {
            if (res.data.totalCount > 0) {
              this.shopListData = res.data.data
              this.doSearch()
            } else {
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
        })
    },
    // 选择日期
    selectStartDay (val) {
      this.startTimeDay = val
      if (val !== '') {
        this.doSearch()
      }
    },
    // 选择月份
    selectStartMonth (val) {
      this.startTimeMonth = val
      if (val !== '') {
        this.doSearch()
      }
    },
    // 微信销售统计
    getwechatmallSalesDaily () {
      if (this.shopId !== '') {
        let param = {}
        param.merchantId = this.$store.state.user.merchantId // 商户id
        param.shopIds = [
          this.shopId
        ] // 门店ID
        param.startDate = this.startDate
        param.endDate = this.endDate
        wechatmallSalesDaily(param)
          .then(res => {
            if (res.data.status === 200) {
              if (res.data.data && res.data.data.length !== 0) {
                let chartList = res.data.data[0].items
                chartList.forEach((element, index) => {
                  element.name = element.productName
                  element.value = element.consumeAmount
                  element.amountRate = element.amountRate
                  element.color = this.chartColor[index]
                })
                this.weChatSalesStatisticsData = chartList
                this.totalAmount = res.data.data[0].totalAmount
                this.weChatShow = true
                this.initChart()
              } else {
                this.weChatShow = false
                this.weChatSalesStatisticsData = []
              }
              this.spinShow = false
            } else {
              this.$Message.error(`${res.data.error}`)
              this.spinShow = false
            }
          })
          .catch(error => {
            this.$Message.error(`${error}`)
            this.spinShow = false
          })
      }
    },
    // 微信销售明细
    getwechatmallSalesList () {
      this.tableHeight = 0
      if (this.shopId !== '') {
        this.loading = true
        let param = {}
        param.merchantId = this.$store.state.user.merchantId // 商户id
        param.shopIds = [
          this.shopId
        ] // 门店ID
        param.startDate = this.startDate
        param.endDate = this.endDate
        param.offset = (this.pageIndex - 1) * this.pageSize // 分页OFFSET
        param.limit = this.pageSize // 分页大小
        wechatmallSalesList(param)
          .then(res => {
            if (res.data.status === 200) {
              if (res.data.data && res.data.data.length !== 0) {
                this.loading = false
                this.wechatData = res.data.data
                this.total = res.data.totalCount
                if (res.data.data && res.data.data.length >= 10) {
                  this.tableHeight = 520
                }
              } else {
                this.wechatData = []
                this.total = 0
                this.loading = false
              }
              this.spinShow = false
            } else {
              this.spinShow = false
              this.loading = false
              this.$Message.error(`${res.data.error}`)
            }
          })
          .catch(error => {
            this.loading = false
            this.$Message.error(`${error}`)
            this.spinShow = false
          })
      }
    }
  },
  mounted () {
    this.getShopList()
  }
}
</script>

<style lang='less'>
#wxdetail {
  .wxdetail-style {
    width: 180px;
    margin-left: 10px;
  }
  .search-item-left {
    width: 90%;
  }
  .system-selete-icon {
    display: inline-block;
    background: #2d8cf0;
    height: 20px;
    width: 8px;
    margin-left: 40px;
    margin-top: 14px;
  }
  .system-selete-title {
    display: inline-block;
    font-family: PingFangSC-Medium;
    font-size: 14px;
    color: #464c5b;
    letter-spacing: 0;
    text-align: justify;
    margin-left: 10px;
  }
  .search-box-title {
    width: 100%;
    height: 48px;
    line-height: 48px;
    background: #f8f8f9;
  }
  .wxdetail-chart-legend {
    width: 50%;
    text-align: left;
    // height: 330px;
  }
  .wxdetail-chart-div {
    width: 100%;
    // position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    // margin: 0 auto;
    padding: 20px 0;
  }
  .chart-pie {
    width: 50%;
    height: 330px;
  }
  #paymentTerm {
    width: 330px;
    height: 330px;
    margin: 0 auto;
  }
  .legend-li {
    width: 100%;
    margin-bottom: 27px;
    display: flex;
    align-items: center;
    .legend-icon {
      display: inline-block;
      width: 12px;
      height: 12px;
    }
    .legend-title {
      font-family: PingFangSC-Regular;
      display: inline-block;
      width: 200px;
      font-size: 12px;
      color: #464c5b;
      margin-left: 10px;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .legend-total {
      font-family: PingFangSC-Medium;
      display: inline-block;
      width: 100px;
      font-size: 14px;
      color: #464c5b;
      letter-spacing: 0;
      text-align: right;
    }
    .legend-percentage {
      font-family: PingFangSC-Regular;
      width: 44px;
      margin-left: 64px;
      display: inline-block;
      font-size: 12px;
      color: #808695;
      letter-spacing: 0;
      text-align: justify;
    }
  }
  .wxdetail-table {
    width: 80%;
    margin: 0 auto;
    margin-top: 48px;
    margin-bottom: 24px;
  }
  .select-shop-item .ivu-select-dropdown {
    width: 300px;
  }
  .select-shop-item .ivu-select-item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
